package cn.schoolwow.quickdao.module.database.dml.json.service.compare;

import cn.schoolwow.quickdao.domain.database.dml.CompareJSONArrayResult;
import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickdao.module.database.dml.json.flow.common.check.CheckUniqueFieldNameFlow;
import cn.schoolwow.quickdao.module.database.dml.json.flow.insert.get.DistinguishExistJSONArrayFlow;
import cn.schoolwow.quickdao.module.database.dml.json.flow.insert.get.GetUniqueFieldValueListFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.jsonarray.QueryJSONArray;
import com.alibaba.fastjson.JSONArray;

import java.util.List;

public class CompareJSONArrayFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        setCompareJSONArrayResult(flowContext);
        setDeleteJSONArray(flowContext);
    }

    @Override
    public String name() {
        return "比较JSON数组复合流程";
    }

    private void setCompareJSONArrayResult(FlowContext flowContext){
        JSONArray currentJSONArray = flowContext.getData("currentJSONArray", JSONArray.class);

        flowContext.putTemporaryData("instances", currentJSONArray);
        flowContext.executeFlowList(
                new CheckUniqueFieldNameFlow(),
                new GetUniqueFieldValueListFlow(),
                new DistinguishExistJSONArrayFlow()
        );
        CompareJSONArrayResult compareJSONArrayResult = new CompareJSONArrayResult();
        compareJSONArrayResult.insertJSONArray = (JSONArray) flowContext.getData("notExistJSONArray");
        compareJSONArrayResult.updateJSONArray = (JSONArray) flowContext.getData("existJSONArray");
        flowContext.putInstanceData(compareJSONArrayResult);
    }

    private void setDeleteJSONArray(FlowContext flowContext){
        JSONArray totalJSONArray = flowContext.getData("totalJSONArray", JSONArray.class);
        if(null==totalJSONArray||totalJSONArray.isEmpty()){
            return;
        }
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        JSONArray currentJSONArray = flowContext.getData("currentJSONArray", JSONArray.class);
        CompareJSONArrayResult compareJSONArrayResult = flowContext.checkInstanceData(CompareJSONArrayResult.class);

        List list = QueryJSONArray.newQuery(currentJSONArray)
                .execute()
                .getMultipleFieldValueList(manipulationOption.uniqueFieldNames);
        compareJSONArrayResult.deleteJSONArray = QueryJSONArray.newQuery(totalJSONArray)
                .addNotInQuery(manipulationOption.uniqueFieldNames, list)
                .execute()
                .getArray();
    }

}
